package com.hnjk.cbts;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.util.component.LifeCycle.Listener;


public class ExamServerAddressSpeaker {
	
	private int serverPort;
	
	// Jetty Server
	private static Server jettyServer;
	// Jetty服务的状态(用处不大)
	private static boolean isStarted;
	// 服务器状态监听器
	private static Listener serverStatusListener = null;
	
	// 测试事件监听的
	private IHandlerListener handlerListener = null;
	
	// 临时的修改一下测试事件机制
	public ExamServerAddressSpeaker(String examServerAddress, IHandlerListener handlerListener) {
		setServerPort(Integer.valueOf(ConfigProperties.getConfig("server_port")));
		
		HandlerList handlerList = new HandlerList();
		ErrorMessageHandler errorMessageHandler = new ErrorMessageHandler();
				
		handlerList.addHandler(errorMessageHandler);
		// changed for listener
		ExamServerAddressHandler examServerAddressHandler = new ExamServerAddressHandler(examServerAddress);
		if(handlerListener != null) {
			examServerAddressHandler.setListener(handlerListener);
		}
		handlerList.addHandler(examServerAddressHandler);
		
			
		jettyServer = new Server();
		ServerConnector connector = new ServerConnector(jettyServer);
		connector.setPort(serverPort);
		jettyServer.setConnectors(new Connector[] { connector });
		jettyServer.setHandler(handlerList);
	}
	
	public void setHandlerListener(IHandlerListener listener) {
		this.handlerListener = listener;
	}
	
	public void setServerStatusListener(Listener listener) {
		serverStatusListener = listener;
	}
	
	public void setServerPort(int serverPort) {
		this.serverPort = serverPort;
	}
	public int getServerPort() {
		return this.serverPort;
	}
	
	public boolean Started() {
		return isStarted;
	}
	public void setStarted(boolean b) {
		isStarted = b;
	}
	
	/**
	 * 启动机考服务地址发布web服务
	 * 放入线程内运行才不会影响界面的其他操作
	 */
	public void start() {
		if(isStarted==false) {
			new Thread() {
				public void run() {					
					try {
						if(serverStatusListener != null) {
							jettyServer.addLifeCycleListener(serverStatusListener);
						}						
						jettyServer.start();
						jettyServer.join();							
					} catch (Exception e) {
						isStarted = false;
						e.printStackTrace();
					}
				};
			}.start();			
		}
	}
	/**
	 * 关闭机考地址发布web服务
	 */
	public void stop() {
		if(jettyServer.isStarted()) {
			try {
				jettyServer.stop();
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}
	}

}
